import { ref, toRaw } from 'vue';
import { dbPromise, STORE_NAME } from '@/utils/db.js';

const chatHistory = ref([]);

export function useChatHistory() {
  const initHistory = async () => {
    const db = await dbPromise;
    const allHistory = await db.getAll(STORE_NAME); 
    chatHistory.value = allHistory.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  };

  const saveToHistory = async (character, messages) => {
    const db = await dbPromise;

    // 查找最后一条文本消息用于生成预览
    const lastUserMessage = messages.slice().reverse().find(m => m.type === 'user' && (!m.subType || m.subType === 'text'));
    const preview = lastUserMessage 
      ? lastUserMessage.text.substring(0, 30) + (lastUserMessage.text.length > 30 ? '...' : '') 
      : '语音对话';

    const newEntry = {
        character: { name: character.name, initials: character.initials, color: character.color },
        messages: toRaw(messages),
        preview: preview,
        timestamp: new Date().toISOString()
    };
    
    await db.put(STORE_NAME, newEntry);
    
    await initHistory();

    if (chatHistory.value.length > 10) {
        const oldestEntryKey = chatHistory.value[chatHistory.value.length - 1].character.name;
        await db.delete(STORE_NAME, oldestEntryKey);
        await initHistory();
    }
  };

  const loadHistory = async (characterName) => {
    const db = await dbPromise;
    const historyItem = await db.get(STORE_NAME, characterName);
    return historyItem ? historyItem.messages : null;
  };

  initHistory();

  return { chatHistory, saveToHistory, loadHistory };
}